package br.com.hstar.client.tabelapreco;

import java.util.ArrayList;
import java.util.List;

import br.com.hstar.client.ServiceFactory;
import br.com.hstar.client.util.FormPanel;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class TabelaPrecoEditPanel extends VerticalPanel{

	private Button incluir;
	private Button limpar;
	private TextBox descricao;
	private TextBox horaEntrada;
	private TextBox horaSaida;
	private TextBox valor;
	private DockPanel dockPanel;//tabela com o titulo azul
	private VerticalPanel dockPanelContent;//painel central do dockpanel
	private FlexTable table;//tabela que vai conter os listboxes para adicionar os precos
	private HorizontalPanel hp = new HorizontalPanel();//painel que vai conter a tabela
	
	public TabelaPrecoEditPanel() {
		dockPanel = new DockPanel();
		dockPanel.setStyleName( "DockPanel" );
		
		//título da tabela
		HTML html = new HTML( "Tabela de Preços" );
		html.setStyleName( "IntPanel-Title" );
		dockPanel.add( html, DockPanel.NORTH );
		
		//conteúdo do dockPanel
		dockPanelContent = new VerticalPanel();
		dockPanelContent.setStyleName( "ContentTable" );
		dockPanel.add( dockPanelContent, DockPanel.CENTER );
		
		//inicializa os botões
		incluir = new Button("Incluir");
		incluir.addClickListener(new ClickListener(){
			public void onClick(Widget sender) {
				PrecoUI p = new PrecoUI();
				p.setDescricao(descricao.getText().trim());
				p.setHoraEntrada(horaEntrada.getText().trim());
				p.setHoraSaida(horaSaida.getText().trim());
				p.setValor(valor.getText().trim().replace(',', '.'));
				
				ServiceFactory.createPrecoService().saveOrUpdate(p, new AddPrecosAsyncCallback());
				
				//limpa os campos
				descricao.setText("");
				horaEntrada.setText("");
				horaSaida.setText("");
				valor.setText("");
			}
		});
		limpar = new Button("Limpar");
		limpar.addClickListener(new ClickListener(){
			public void onClick(Widget sender) {
				descricao.setText("");
				horaEntrada.setText("");
				horaSaida.setText("");
				valor.setText("");
			}
		});
		
		init();
	}
	
	private void init() {
		table = new FlexTable();
		descricao   = FormPanel.addTextBox("", 30, 30, "");
		horaEntrada = FormPanel.addTextBox("", 30, 30, "");
		horaSaida   = FormPanel.addTextBox("", 30, 30, "");
		valor   	= FormPanel.addTextBox("", 30, 30, "");
		
		table.setWidget(0,0,new Label("Descricao: "));
		table.setWidget(0,1,descricao);
		table.setWidget(1,0,new Label("Duração / Hora Entrada: "));
		table.setWidget(1,1,horaEntrada);
		table.setWidget(2,0,new Label("Hora Saída: "));
		table.setWidget(2,1,horaSaida);
		table.setWidget(3,0,new Label("Valor: "));
		table.setWidget(3,1,valor);
		HorizontalPanel but = new HorizontalPanel();
		but.add(incluir);but.add(limpar);
		table.setWidget(4,1,but);
		
		hp.add(table);
		this.add(hp);
		this.add(dockPanel);
		
		//lista todos os preços existentes
		ServiceFactory.createPrecoService().listAll(new ListAllPrecosAsyncCallback());
	}
	
	public void addPreco(final PrecoUI preco) {
		//adicoina o ítem visual
		//essa implementacao do Image contem o PordutoDO.
		final MyPrecoImage img = new MyPrecoImage( getImageUrl("img/remove.png") );
		img.setPreco(preco);
		
		final HorizontalPanel vp = new HorizontalPanel();
		vp.add(new HTML(preco.getDescricao()+" - "+
						preco.getHoraEntrada()+(preco.getHoraSaida().trim().equals("")? " " : " às ")+
						preco.getHoraSaida()+" R$"+
						preco.getValor()));
		vp.add(img);
		
		dockPanelContent.add(vp);
		img.addClickListener(new ClickListener(){
			public void onClick(Widget arg0) {
				if(Window.confirm("Deseja realmente excluir este registro?")) {
					removePreco(vp, preco);
				}
			}
		});
	}
	public void removePreco(Widget wid, PrecoUI preco) {
		dockPanelContent.remove(wid);
		ServiceFactory.createPrecoService().delete(preco.getId(), new RemovePrecosAsyncCallback());
	}
	
	
	//adiciona o preco novo
	private class AddPrecosAsyncCallback implements AsyncCallback {
		public void onFailure(Throwable caught) {
			Window.alert("erro ao adicionar um preço");
		}
		public void onSuccess(Object result) {
			Window.alert("Registro adicionado com sucesso!");
			ServiceFactory.createPrecoService().listAll(new ListAllPrecosAsyncCallback());
		}
	}
	
	//remove o preço da lista e do banco de dados
	private class RemovePrecosAsyncCallback implements AsyncCallback {
		public void onFailure(Throwable caught) {
			Window.alert("erro ao listar os preços");
		}
		public void onSuccess(Object result) {
			Window.alert("Registro excluído com sucesso!");
			ServiceFactory.createPrecoService().listAll(new ListAllPrecosAsyncCallback());
		}
	}
	
	//lista todos os precos existentes
	private class ListAllPrecosAsyncCallback implements AsyncCallback {
		public void onFailure(Throwable caught) {
			Window.alert("erro ao listar os preços");
		}
		public void onSuccess(Object result) {
			List precos = (ArrayList)result;
			dockPanelContent.clear();
			for (int i = 0; i < precos.size(); i++) {
				PrecoUI p = (PrecoUI)precos.get(i);
				addPreco(p);
			}
		}
	}
	
	public static String getImageUrl( String relImgUrl ) {
		return GWT.getModuleBaseURL() + relImgUrl;
	}
}